# # --*-- conding:utf-8 --*--
# # @Time : 2025/6/22 22:58
# # @Author : XU
# # @Email : wsxzy98@outlook.com
# # @File : stock_picking_pack_patch.py
# # @Software : VScode

# from odoo import models, api
# from collections import defaultdict

# # 此patch用于按客户参考号分组打包，每个不同客户明细分行生成quant
# class StockPicking(models.Model):
#     _inherit = 'stock.picking'

#     @api.model
#     def _group_move_lines_for_pack(self, move_line_ids):
#         """分组move_line，核心是customer_reference参与分组"""
#         group_dict = defaultdict(list)
#         for ml in move_line_ids:
#             key = (
#                 ml.product_id.id,
#                 ml.location_dest_id.id,
#                 ml.lot_id.id if ml.lot_id else None,
#                 ml.owner_id.id if ml.owner_id else None,
#                 ml.customer_reference,
#             )
#             group_dict[key].append(ml)
#         return group_dict

#     def action_put_in_pack(self, move_lines_to_pack=False):
#         """
#         二开此方法，实现按customer_reference分组打包。
#         """
#         self.ensure_one()
#         if self.state in ('done', 'cancel'):
#             return
#         # 兼容官方逻辑
#         move_line_ids = self._package_move_lines(move_lines_to_pack=move_lines_to_pack)
#         if not move_line_ids:
#             raise UserError(_("There is nothing eligible to put in a pack. Either there are no quantities to put in a pack or all products are already in a pack."))

#         # ====== 关键patch：按分组分别create quant ======
#         group_dict = self._group_move_lines_for_pack(move_line_ids)
#         for key, move_lines in group_dict.items():
#             # 新建包裹
#             package = self.env['stock.quant.package'].create({})
#             # 把该组所有明细写到新包裹里
#             move_lines.write({'result_package_id': package.id})

#             # 生成包裹层级对象（原生代码里可有可无）
#             if len(self) == 1:
#                 self.env['stock.package.level'].with_context(from_put_in_pack=True).create({
#                     'package_id': package.id,
#                     'picking_id': self.id,
#                     'location_id': False,
#                     'location_dest_id': move_lines[0].location_dest_id.id,
#                     'move_line_ids': [(6, 0, move_lines.ids)],
#                     'company_id': self.company_id.id,
#                 })
#             # 关键：每组分开create quant，customer_reference能分行保存
#             quant_vals = {
#                 'product_id': key[0],
#                 'location_id': key[1],
#                 'lot_id': key[2],
#                 'owner_id': key[3],
#                 'package_id': package.id,
#                 'customer_reference': key[4],
#                 'quantity': sum(ml.qty_done for ml in move_lines),
#             }
#             self.env['stock.quant'].create(quant_vals)
#         return True
